package com.example.util;

import java.sql.*;
import java.util.ResourceBundle;

/**
 * 数据库连接工具类
 */
public class DBUtil {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;
    
    // 静态代码块，加载配置文件
    static {
        try {
            // 从配置文件读取数据库连接信息
            ResourceBundle bundle = ResourceBundle.getBundle("db");
            driver = bundle.getString("driver");
            url = bundle.getString("url");
            username = bundle.getString("username");
            password = bundle.getString("password");
            
            // 加载驱动
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 获取数据库连接
     * @return Connection对象
     */
    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    
    /**
     * 关闭数据库连接资源
     * @param conn 连接对象
     * @param stmt Statement对象
     * @param rs ResultSet对象
     */
    public static void close(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
} 